package code.example.base.util.concurrent.lock.countdownlatch;

import code.example.tool.LogFactory;

import java.util.concurrent.TimeUnit;

public class ICountDownLatchSync implements ICountDownLatch {
    int count ;
    public ICountDownLatchSync (int count){
       this.count = count;
    }
    @Override
    public synchronized  void countdown() {
        count --;
        LogFactory.getLog().info("countdown:"+Thread.currentThread().getName()+" :count down :"+count);
        if(count ==0){
            LogFactory.getLog().info(Thread.currentThread().getName()+" :to wake up");
            this.notifyAll();
        }
    }

    @Override
    public synchronized void await() {
        await(0,TimeUnit.SECONDS);
    }

    @Override
    public boolean  await(int timeout, TimeUnit timeUnit) {
        long mills = timeUnit.toMillis(timeout);
        long endTimeMill = System.currentTimeMillis()+mills;
        for(;;){
            long timeOutMill =endTimeMill - System.currentTimeMillis();
            try {
                if(count ==0){
                    return true;
                }else if(timeout<=0){
                    LogFactory.getLog().info("await :to block thread: to park thread: "+Thread.currentThread().getName());
                        this.wait();
                   // LogFactory.getLog().info(Thread.currentThread().getName()+" :to wake up finish");
                }else if(timeOutMill<=0){
                     return false;
                }else{
                    LogFactory.getLog().info("await :to block thread: to park thread: "+Thread.currentThread().getName());
                    this.wait(timeOutMill);
                   // LogFactory.getLog().info(Thread.currentThread().getName()+" :to wake up finish");
                }
            }catch (InterruptedException e){
                //ignore interrupted
            }
        }
    }
}
